package by.grsu.eo.pages;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.eo.dao.UserDao;
import by.grsu.eo.page.MainWebPage;
import by.grsu.eo.payment.system.User;

public class EditUser extends MainWebPage {
	
	@SpringBean
	private UserDao userDao;

	@SuppressWarnings("serial")
	public EditUser(final User userToEdit) {
		super();

		// create form fields and set data
		final TextField<String> firstnameField = new TextField<String>("firstName", new Model<String>(userToEdit.getFirstName()));
		final TextField<String> LastnameField = new TextField<String>("lastName", new Model<String>(userToEdit.getLastName()));
		final TextField<String> loginField = new TextField<String>("login", new Model<String>(userToEdit.getLogin()));
		final TextField<String> passwordField = new TextField<String>("password", new Model<String>(userToEdit.getPassword()));
		//final DropDownChoice<String> roleField = new DropDownChoice<String>("role", new Model<String>(userToEdit.getRole().toString()), Arrays.asList(Role.values().toString()));

		// create "form" component which is required for data retrieving from
		// client to server
		Form<User> form = new Form<User>("editUser", new Model<User>(userToEdit)) {
			@Override
			public void onSubmit() {
				// retrieve data from the form and set it to the object
				userToEdit.setFirstName(firstnameField.getModelObject());
				userToEdit.setLastName(LastnameField.getModelObject());
				userToEdit.setLogin(loginField.getModelObject());
				userToEdit.setPassword(passwordField.getModelObject());
				/*if("administrator".equals(roleField.getModelObject())){
					userToEdit.setRole(Role.administrator);
				} else {
					userToEdit.setRole(Role.cardUser);
				}*/
				// save updated object in DB	
				userDao.save(userToEdit);
				// go to the list page
				setResponsePage(ListUsers.class);
			}
		};

		// add form fields
		form.add(firstnameField);
		form.add(LastnameField);
		form.add(loginField);
		form.add(passwordField);
		//form.add(roleField);

		// add buttons
		form.add(new Button("saveLink"));
		form.add(new Link<User>("cancelLink") {

			@Override
			public void onClick() {
				setResponsePage(ListUsers.class);
			}
		});
		// add form to the page
		add(form);

		// add special component which will allow to display "validation errors"
		// and feedback messages
		FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
		add(feedbackPanel);
	}
	
}
